package com.smec.moblie.activity;

import android.app.Activity;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.CircleOptions;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Stroke;
import com.baidu.mapapi.model.LatLng;
import com.smec.moblie.R;
import com.smec.moblie.bean.Gps;
import com.smec.moblie.control.EventCenter;
import com.smec.moblie.crash.ExitAppUtils;
import com.smec.moblie.util.PositionUtil;

import de.greenrobot.event.EventBus;

/**
 * 电子围栏activity
 *
 * @author sunyubo
 */
public class ElectronicFenceMapActivity extends Activity {
    // 基本地图
    private MapView mMapView = null;
    // 按钮确认到达
    private Button button_arrived;
    // 按钮取消
    private Button button_cancel;
    // 定位图层
    private BaiduMap mBaiduMap;
    // 定位相关
    private LocationClient mLocClient;
    // 刚进入是否启动定位
    private Boolean isFirstLoc = true;
    // 定位模式
    private LocationMode mCurrentMode;
    private BitmapDescriptor mCurrentMarker = null;
    private BDLocation mylocation = null;
    private MyLocationListenner myLocationListenner;
    // 方向管理
    private SensorManager sensorManager;
    // 方向监听
    private MySensorEventListener mySensorEventListener;
    // 当前的方向
    private float x;
    /**
     * 记录列表页点击的位置，详情页是-1
     **/
    private int position;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 隐去标题栏
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_electronicfencemap);
        ExitAppUtils.getInstance().addActivity(this);
        Intent intent = getIntent();
        position = intent.getIntExtra("position", -1);
        // 获取地图控件引用
        mMapView = (MapView) findViewById(R.id.bmapView);
        // 获取定位图层
        mBaiduMap = mMapView.getMap();
        // 添加电子围栏圆圈
        Gps gps = PositionUtil.gcj02_To_Bd09(
                intent.getDoubleExtra("latitude", 0),
                intent.getDoubleExtra("longitude", 0));
        LatLng llCircle = new LatLng(gps.getWgLat(), gps.getWgLon());
        OverlayOptions ooCircle = new CircleOptions().fillColor(0x000000FF)
                .center(llCircle).stroke(new Stroke(2, 0xAA1E90FF)).radius(500);
        mBaiduMap.addOverlay(ooCircle);
        // 初始化获取方向服务
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        mySensorEventListener = new MySensorEventListener();

        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        mCurrentMode = LocationMode.FOLLOWING;// 设置为跟随模式
        mBaiduMap.setMyLocationConfigeration(new MyLocationConfiguration(
                mCurrentMode, true, mCurrentMarker));
        // 定位初始化
        mLocClient = new LocationClient(this);
        myLocationListenner = new MyLocationListenner();
        mLocClient.registerLocationListener(myLocationListenner);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);// 打开gps
        option.setCoorType("gcj02"); // 设置坐标类型
        option.setScanSpan(1000);
        mLocClient.setLocOption(option);
        mLocClient.start();
        mBaiduMap.setMapStatus(MapStatusUpdateFactory
                .newMapStatus(new MapStatus.Builder().zoom(15).build()));// 设置缩放等级

        button_cancel = (Button) findViewById(R.id.button_cancel);
        button_arrived = (Button) findViewById(R.id.button_arrived);
        button_cancel.setOnClickListener(new MyOnClickListener());
        button_arrived.setOnClickListener(new MyOnClickListener());
    }

    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mMapView == null || mBaiduMap == null)
                return;
            mylocation = location;
            Gps gps = PositionUtil.gcj02_To_Bd09(mylocation.getLatitude(),
                    mylocation.getLongitude());
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                            // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(x).latitude(gps.getWgLat())
                    .longitude(gps.getWgLon()).build();
            mBaiduMap.setMyLocationData(locData);
            mCurrentMode = LocationMode.NORMAL;// 设置为普通模式
            mBaiduMap.setMyLocationConfigeration(new MyLocationConfiguration(
                    mCurrentMode, true, mCurrentMarker));
            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng ll = new LatLng(gps.getWgLat(), gps.getWgLon());
                MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
                mBaiduMap.animateMapStatus(u);
            }
        }

        public void onReceivePoi(BDLocation poiLocation) {
        }
    }

    @SuppressWarnings("deprecation")
    @Override
    protected void onResume() {
        // 注册方向事件监听
        Sensor sensor_orientation = sensorManager
                .getDefaultSensor(Sensor.TYPE_ORIENTATION);

        sensorManager.registerListener(mySensorEventListener,
                sensor_orientation, SensorManager.SENSOR_DELAY_UI);
        super.onResume();
        // 在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume();
    }

    @Override
    protected void onPause() {

        super.onPause();
        // 注销方向事件监听
        sensorManager.unregisterListener(mySensorEventListener);
        mMapView.onPause();

    }

    @Override
    protected void onDestroy() {
        // 退出时销毁定位
        mLocClient.stop();
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        mMapView.onDestroy();
        mMapView = null;
        super.onDestroy();

    }

    /**
     * 获取方向信息并更新地图箭头方向监听
     *
     * @author sunyubo
     */
    private class MySensorEventListener implements SensorEventListener {

        @Override
        public void onSensorChanged(SensorEvent event) {
            // 获取方向角度0-360
            x = event.values[0];
            if (null != mylocation) {
                Gps gps = PositionUtil.gcj02_To_Bd09(mylocation.getLatitude(),
                        mylocation.getLongitude());
                // 重新赋值到地图
                MyLocationData locData = new MyLocationData.Builder()
                        .accuracy(mylocation.getRadius())
                                // 此处设置开发者获取到的方向信息，顺时针0-360
                        .direction(x).latitude(gps.getWgLat())
                        .longitude(gps.getWgLon()).build();
                mBaiduMap.setMyLocationData(locData);
            }
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {

        }

    }

    /**
     * 按钮点击监听
     **/
    private class MyOnClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.button_arrived:
                    if (null == mylocation) {
                        mylocation = new BDLocation();
                        mylocation.setLatitude(0.0);
                        mylocation.setLongitude(0.0);
                    }
                    EventBus.getDefault().post(new EventCenter.MapBack(mylocation.getLongitude(), mylocation.getLatitude(), position));
                    ElectronicFenceMapActivity.this.finish();
                    break;
                case R.id.button_cancel:
                    ElectronicFenceMapActivity.this.finish();
                    break;
                default:
                    break;
            }

        }
    }
}
